import qiniu


class QiniuUploader(object):
    def __init__(self, *args, **kwargs):
        self._access_key = None
        self._secret_key = None
        pass

    def init_app(self, app):
        if app:
            self._access_key = app.config.get('QINIU_ACCESS_KEY')
            self._secret_key = app.config.get('QINIU_SECRET_KEY')
            self._bucket_name = app.config.get('QINIU_BUCKET_NAME')
            self._base_url = app.config.get('QINIU_BASE_URL')
            self._auth = qiniu.Auth(self._access_key, self._secret_key)
        else:
            pass

    def put_file(self, file_name, file_path, *args, **kwargs):
        up_token = self._auth.upload_token(self._bucket_name)
        ret, info = qiniu.put_file(up_token, file_name, file_path)
        if not ret:
            print('UPLOAD ERROR: ', info)
        else:
            return ret

    def put_stream(self, file_name, stream, *args, **kwargs):
        up_token = self._auth.upload_token(self._bucket_name)
        ret, info = qiniu.put_stream(up_token, file_name, stream, len(stream))
        if not ret:
            print('UPLOAD ERROR: ', info)
        else:
            return ret

    def url_for(self, file_name):
        return '{}/{}'.format(self._base_url, file_name)

    def type(self):
        return 'qiniu'
